<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>提醒事件</title>
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    body {
      background-image: linear-gradient(90deg, #e0c3fc 0%, #8ec5fc 100%);

    }

    li {
      list-style: none;
    }

    /* 字体 */
    @font-face {
      font-family: 字体1;
      src: url(font-family/ruizichaopaizhenyandacu.ttf);
    }

    @font-face {
      font-family: 字体2;
      src: url(font-family/ALTERNATIVEROCK-Border.ttf);
    }

    @font-face {
      font-family: 字体3;
      src: url(font-family/ALTERNATIVEROCK.ttf);
    }

    @font-face {
      font-family: 字体4;
      src: url(font-family/hanyifengboxiaomuwufan.ttf);
    }

    @font-face {
      font-family: 字体5;
      src: url(font-family/汉仪铸字妙想繁体.ttf);
    }

    .header {
      height: 60px;
      background-image: linear-gradient(90deg, #e0c3fc 0%, #8ec5fc 100%);

      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 30px;
      color: #fff;
      text-shadow: 1px 1px 1px rgba(249, 248, 248, 0.5);

      font-family: 字体1;
    }

    .container {
      display: flex;
      justify-content: center;
      align-items: flex-start;
      padding-top: 20px;
    }


    /* 事件展示 */
    .list {
      width: 450px;
      margin-right: 20px;
      /* border: 1px solid #999; */
      border-radius: 20px;
      padding: 10px;
      box-shadow: 0px 10px 30px #00000020;
      background-color: rgba(225, 225, 225, 0.43);


    }

    .list-header {
      font-size: 20px;
      font-family: 字体1;
      font-weight: bold;
      text-align: center;
      margin-bottom: 10px;
      height: 40px;
      line-height: 40px;
      border-radius: 5px;
      text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.5);

    }



    .list li {
      margin-bottom: 10px;
      font-size: 16px;
      line-height: 24px;
      border-radius: 10px;
      /* background-color: rgb(189, 226, 22); */
      background-image: linear-gradient(90deg, #b5e4fa 0%, #e8d6fa 100%);
      background-color: #fff;
      box-shadow: 0 10px 10px #00000026;
      text-shadow: 0px 0px 20px #ffffff;


    }

    .list span {
      font-weight: bold;
      margin-right: 10px;
      margin-left: 10px;
      margin-top: 5px;
      font-family: 字体4;
    }

    .list button {
      margin-left: 10px;
      margin-bottom: 5px;
      width: 40px;
      height: 20px;
      line-height: 15px;
      border-radius: 5px;
      border: none;
      background-color: rgba(31, 115, 218, 0.8);
      color: #fff;
      font-family: 字体1;
    }

    .list button:hover {
      background-color: rgba(23, 80, 150, 0.8);

    }


    .list .time {
      color: red;
    }

    .add-form {
      width: 400px;
      border: 1px solid #999;
      background-image: url(image/kangna1.jpeg);

      background-repeat: no-repeat;
      background-position: 0% 30%;
      background-size: 400px 500px;
      border-radius: 25px;
      padding: 10px;
      display: none;
      margin-left: 100px;
      box-shadow: 5px 5px 10px rgba(0, 0, 0, .5);
      border: 5px solid #f4f4f4;
      font-family: 字体1;

    }

    .add-form h2 {
      font-size: 30px;
      margin-bottom: 20px;
      /* color: #ccc; */
    }

    .add-form label {
      display: block;
      margin-bottom: 10px;
      font-size: 16px;
    }

    .add-form input[type="text"],
    .add-form input[type="datetime-local"] {
      width: 100%;
      height: 30px;
      font-size: 14px;
      padding-left: 5px;
      border: 1px solid #ccc;
      border-radius: 3px;
      box-shadow: inset 0px 1px 3px rgba(0, 0, 0, 0.1);
    }

    .add-form button {
      display: block;
      margin-top: 10px;
      width: 100%;
      height: 40px;
      background-image: linear-gradient(90deg, #e0c3fc 0%, #8ec5fc 100%);
      color: #fff;
      font-size: 16px;
      border: none;
      border-radius: 20px;
      cursor: pointer;
    }

    .add-form button:hover {
      background-image: linear-gradient(90deg, #c8afdf 0%, #81b1e2 100%);
    }


    /* 新建按钮 */
    .new_flie {
      position: fixed;
      top: 70px;
      right: 10px;
    }

    .new_flie button {
      background-color: transparent;
      background-image: url(image/naozhong.png);
      background-repeat: no-repeat;
      background-size: contain;
      border: none;
      width: 80px;
      height: 80px;
    }

    .new_flie button:hover {
      background-image: url(image/naozhong_hover.png);
    }

    /* 弹出图片 */
    .popup {
      position: fixed;
      top: 50px;
      left: 40%;
    }

    .popup .image_h2 {
      text-align: center;
      color: rgb(8, 8, 8);
      font-family: 字体4;
      font-size: 35px;
    }

    .popup img {
      width: 300px;
      height: 300px;
    }

    /* 注销按钮 */
    .zhuxiao {
      position: fixed;
      top: 10px;
      right: 10px;

    }

    .zhuxiao button {
      background-image: linear-gradient(to bottom right, #7eb9f4 0%, #c28ff6 100%);

      width: 80px;
      height: 40px;
      border-radius: 20px;
      border: none;
      font-size: 20px;
      font-family: 字体4;

    }

    .zhuxiao button:hover {
      background-image: linear-gradient(to bottom right, #82b3e3 0%, #c6a9e2 100%);
      color: #fff;


    }
  </style>
</head>

<body>
  <div class="header">提醒事件</div>
  <div class="container">
    <div class="list">
      <div class="list-header">待完成</div>
      <ul class="uncompleted-list"></ul>
    </div>
    <div class="list">
      <div class="list-header">已完成</div>
      <ul class="completed-list"></ul>
    </div>

    <!-- 新建按键 -->
    <div class="new_flie">
      <button></button>
    </div>
    <div class="zhuxiao">
      <button onclick="logout()">注销</button>
    </div>

    <div class="add-form">
      <h2>添加提醒</h2>
      <form id="addForm">
        <label>事件名称</label>
        <input type="text" name="name" required>
        <label>地点</label>
        <input type="text" name="address" required>
        <label>备注</label>
        <input type="text" name="beizhu" required>
        <label>截止时间</label>
        <input type="datetime-local" name="time" required>
        <button type="submit">添加</button>
      </form>
    </div>
  </div>
  <script>
    function logout() {
      if (confirm("确定注销?")) {
        // 1.去除后端的 session
        jQuery.ajax({
          url: "/user/logout",
          type: "GET",
          date: {},
          success: function (res) { }
        });
        // 2.跳转到登录页面
        location.href = "login.html";
      }
    }


    var addForm = document.querySelector('#addForm');
    var uncompletedList = document.querySelector('.uncompleted-list');
    var completedList = document.querySelector('.completed-list');


    //新建按钮
    var new_flie = document.querySelector('.new_flie');
    var new_btn = new_flie.querySelector('button');
    var add_from = document.querySelector('.add-form');
    var submit_btn = add_from.querySelector('button');

    new_btn.onclick = function () {
      add_from.style.display = 'block';
      new_flie.style.display = 'none';

    }
    // 添加提醒事件
    addForm.addEventListener('submit', function (e) {
      new_flie.style.display = 'block';
      add_from.style.display = 'none';
      //e.preventDefault()来阻止表单提交后刷新页面的默认行为
      e.preventDefault();

      // 获取表单数据
      var formData = new FormData(addForm);
      var name = formData.get("name");
      var address = formData.get("address");
      var beizhu = formData.get("beizhu");
      var time = formData.get("time");
      var newStr = time.replace(/T/g, " ");
      console.log(time);
      console.log(newStr);


      // 创建待完成列表项
      var li = document.createElement("li");
      li.innerHTML =
        "<span>事项：" +
        name +
        "</span><br/>" +
        "<span>地点：" +
        address +
        "</span><br/>" +
        "<span>备注：" +
        beizhu +
        "</span><br/>" +
        '<span class="time"></span>' +
        '<button class="complete-btn">完成</button>' +
        '<button class="delete-btn">删除</button>';
      var index = 1;

      // 计算倒计时
      var deadline = new Date(time).getTime();
      var timer = setInterval(function () {
        var now = new Date().getTime();
        var remainingTime = deadline - now;
        var days = Math.floor(remainingTime / (1000 * 60 * 60 * 24));
        var hours = Math.floor((remainingTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = Math.floor((remainingTime % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((remainingTime % (1000 * 60)) / 1000);

        var timeSpan = li.querySelector('.time');
        timeSpan.textContent = `剩余时间：${days}天${hours}小时${minutes}分${seconds}秒`;



        console.log(remainingTime);
        if (remainingTime < 0) {
          clearInterval(timer);
          timeSpan.textContent = '已超时';
          //倒计时结束直接删除完成按钮
          li.removeChild(completeBtn);

          // disabled 禁用确定按钮
          // li.querySelector('.complete-btn').disabled = true;
        }
        if (remainingTime <= 30000) {
          if (index > 0) {
            console.log("提醒");
            // 创建弹出框元素
            var popup = document.createElement('div');
            popup.className = 'popup';
            // // 创建退出按钮
            // var tuichu = document.createElement('img')
            // tuichu.src = 'image/cuowu.png';
            // 创建图片元素
            var image = document.createElement('img');
            image.src = 'image/kangnatixing4.png';
            //创建文本
            var image_h2 = document.createElement('div');
            image_h2.className = 'image_h2';
            image_h2.innerHTML = `<span>${name}</span>`;
            // 将图片添加到弹出框中

            popup.appendChild(image);
            popup.appendChild(image_h2);

            // popup.appendChild(tuichu);

            // 将弹出框添加到页面中
            document.body.appendChild(popup);

            image.onclick = function () {
              popup.style.display = 'none';
            }

          }
          index = -1;


        }

      }, 1000);

      // ============这里需要访问数据库，将任务添加到数据库中=============
      jQuery.ajax({
        url: "/task/add",
        type: "post",
        data: {
          name: name,
          date: newStr,
          place: address,
          remark: beizhu,
        },
        success: function (res) {
          if (res.code == 0) {
            // 添加待完成列表项
            uncompletedList.appendChild(li);
            // 弹窗提醒：添加成功!
            alert("恭喜：添加成功！");
          } else {
            alert("添加失败：" + res.message);
          }
        },
      });


      // 绑定完成按钮点击事件
      var completeBtn = li.querySelector('.complete-btn');
      var new_timeSpan = li.querySelector('.time');
      completeBtn.addEventListener('click', function () {
        // 这段逻辑用于获取事项名
        var firstSpanText = li.querySelector("span").textContent;
        var index = firstSpanText.lastIndexOf("：");
        var text = firstSpanText.substr(index + 1);
        console.log("完成任务" + text);

        clearInterval(timer);
        li.removeChild(completeBtn);

        li.removeChild(new_timeSpan);
        // li.removeChild(li.querySelector('.delete-btn'));

        // 增加已完成列表项
        completedList.appendChild(li);
        
        // ================ 点击完成按钮，更新任务状态 ===================
        jQuery.ajax({
          url: "/task/update",
          type: "post",
          data: {
            name: text,
          },
          success: function (res) {
            if (res.code == 0) {
              // 增加已完成列表项
              completedList.appendChild(li);
              // 弹窗提醒：更新成功!
              alert("恭喜：任务完成！");
            } else {
              alert("更新状态失败：" + res.message);
            }
          },
        });
      });

      // 绑定删除按钮点击事件
      var deleteBtn = li.querySelector(".delete-btn");
      deleteBtn.addEventListener("click", function () {
        // 这段逻辑用于获取事项名
        var firstSpanText = li.querySelector("span").textContent;
        var index = firstSpanText.lastIndexOf("：");
        var text = firstSpanText.substr(index + 1);
        console.log("删除任务：" + text);
        // ================ 点击删除按钮，删除指定任务 ===================
        jQuery.ajax({
          url: "/task/delete",
          type: "post",
          data: {
            name: text,
          },
          success: function (res) {
            if (res.code == 0) {
              // 将元素li移除
              clearInterval(timer);
              li.parentElement.removeChild(li);
              // 弹窗提醒：更新成功!
              alert("恭喜：删除成功！");
            } else {
              alert("删除失败：" + res.message);
            }
          },
        });
        // clearInterval(timer);
        // li.parentElement.removeChild(li);
      });

      // 清空表单
      addForm.reset();

    });


    // ================ 这里是查询数据库并显示到前端页面的逻辑 ===================
    // 页面加载完成后发送请求获取任务数据
    window.addEventListener("load", function () {
      // 发送Ajax请求获取任务数据
      jQuery.ajax({
        url: "/task/getall",
        type: "get",
        success: function (res) {
          if (res.code == 0) {
            var tasks = res.data;
            // 遍历任务数据
            tasks.forEach(function (task) {
              if (task.isDone == 1) {
                // 已完成任务
                createCompletedTaskItem(task);
              } else if (task.isDone == 0) {
                // 未完成任务
                createUncompletedTaskItem(task);
              } else {
                createExceedTaskItem(task);
              }
            });
          } else {
            alert("获取任务数据失败：" + res.message);
          }
        },
      });
    });

    // 创建已超时任务列表项
    function createExceedTaskItem(task) {
      var li = document.createElement("li");
      li.innerHTML =
        "<span>事项：" +
        task.name +
        "</span><br/>" +
        "<span>地点：" +
        task.place +
        "</span><br/>" +
        "<span>备注：" +
        task.remark +
        "</span><br/>" +
        '<span class="time"></span>' +
        '<button class="complete-btn">完成</button>' +
        '<button class="delete-btn">删除</button>';

      // 绑定删除按钮点击事件
      var deleteBtn = li.querySelector(".delete-btn");
      deleteBtn.addEventListener("click", function () {
        // 将任务从列表中移除
        li.parentElement.removeChild(li);

        // 删除任务
        deleteTask(task.name);
      });
      var timeSpan = li.querySelector(".time");
      timeSpan.textContent = "已超时";
      // 禁用完成按钮
      let complete = li.querySelector(".complete-btn");
      li.removeChild(complete);


      // 将任务添加到待完成列表
      uncompletedList.appendChild(li);
    }

    // 创建已完成的任务列表项
    function createCompletedTaskItem(task) {
      var li = document.createElement("li");
      li.innerHTML =
        "<span>事项：" +
        task.name +
        "</span><br/>" +
        "<span>地点：" +
        task.place +
        "</span><br/>" +
        "<span>备注：" +
        task.remark +
        "</span><br/>" +
        '<button class="delete-btn">删除</button>';

      // 绑定删除按钮点击事件
      var deleteBtn = li.querySelector(".delete-btn");
      deleteBtn.addEventListener("click", function () {
        // 将任务从列表中移除
        li.parentElement.removeChild(li);

        // 删除任务
        deleteTask(task.name);
      });

      completedList.appendChild(li);

      // var li = document.createElement('li');
      // li.innerHTML =
      //     '<span>事项：' + task.name + '</span><br/>'
      //     + '<span>地点：' + task.place + '</span><br/>'
      //     + '<span>备注：' + task.remark + '</span><br/>';

      // completedList.appendChild(li);
    }

    // 创建未完成的任务列表项
    function createUncompletedTaskItem(task) {
      var li = document.createElement("li");
      li.innerHTML =
        "<span>事项：" +
        task.name +
        "</span><br/>" +
        "<span>地点：" +
        task.place +
        "</span><br/>" +
        "<span>备注：" +
        task.remark +
        "</span><br/>" +
        '<span class="time"></span>' +
        '<button class="complete-btn">完成</button>' +
        '<button class="delete-btn">删除</button>';

      var index = 1;

      // 计算倒计时
      var deadline = new Date(task.date).getTime();
      var timer = setInterval(function () {
        var now = new Date().getTime();
        var remainingTime = deadline - now;
        var days = Math.floor(remainingTime / (1000 * 60 * 60 * 24));
        var hours = Math.floor((remainingTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = Math.floor((remainingTime % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((remainingTime % (1000 * 60)) / 1000);

        var timeSpan = li.querySelector('.time');
        timeSpan.textContent = `剩余时间：${days}天${hours}小时${minutes}分${seconds}秒`;



        console.log(remainingTime);
        if (remainingTime < 0) {
          clearInterval(timer);
          timeSpan.textContent = '已超时';
          //倒计时结束直接删除完成按钮
          let complete = li.querySelector(".complete-btn");
          li.removeChild(complete);
          // li.removeChild(completeBtn);

          // disabled 禁用确定按钮
          // li.querySelector('.complete-btn').disabled = true;
        }
        if (remainingTime <= 30000) {
          if (index > 0) {
            console.log("提醒");
            // 创建弹出框元素
            var popup = document.createElement('div');
            popup.className = 'popup';
            // // 创建退出按钮
            // var tuichu = document.createElement('img')
            // tuichu.src = 'image/cuowu.png';
            // 创建图片元素
            var image = document.createElement('img');
            image.src = 'image/kangnatixing4.png';
            //创建文本
            var image_h2 = document.createElement('div');
            image_h2.className = 'image_h2';

            image_h2.innerHTML = `<span>${name}</span>`;
            // 将图片添加到弹出框中

            popup.appendChild(image);
            popup.appendChild(image_h2);

            // popup.appendChild(tuichu);

            // 将弹出框添加到页面中
            document.body.appendChild(popup);

            image.onclick = function () {
              popup.style.display = 'none';
            }

          }
          index = -1;
        }

      }, 1000);

      // 绑定完成按钮点击事件
      var completeBtn = li.querySelector(".complete-btn");
      completeBtn.addEventListener("click", function () {
        clearInterval(timer);
        li.removeChild(completeBtn);

        li.removeChild(li.querySelector(".time"));

        // 将任务移动到已完成列表
        completedList.appendChild(li);

        // 更新任务状态为已完成
        updateTaskStatus(task.name);
      });

      // 绑定删除按钮点击事件
      var deleteBtn = li.querySelector(".delete-btn");
      deleteBtn.addEventListener("click", function () {
        // 将任务从列表中移除
        clearInterval(timer);
        li.parentElement.removeChild(li);

        // 删除任务
        deleteTask(task.name);
      });

      // 将任务添加到待完成列表
      uncompletedList.appendChild(li);
    }

    // 更新任务状态
    function updateTaskStatus(taskName) {
      jQuery.ajax({
        url: "/task/update",
        type: "post",
        data: {
          name: taskName,
        },
        success: function (res) {
          if (res.code != 0) {
            alert("更新任务状态失败：" + res.message);
          } else {
            alert("恭喜：任务完成！");
          }
        },
      });
    }

    // 删除任务
    function deleteTask(taskName) {
      jQuery.ajax({
        url: "/task/delete",
        type: "post",
        data: {
          name: taskName,
        },
        success: function (res) {
          if (res.code != 0) {
            alert("删除任务失败：" + res.message);
          } else {
            alert("恭喜：删除成功！");
          }
        },
      });
    }
  </script>
</body>

</html>